<?php
# Враппер для ImageMagick
class WImage {
	
	static function extentThumbnailImage($filename, $w = null, $h = null){
		$image = new Imagick($filename);
		$height = $image->getImageHeight();
		$width = $image->getImageWidth();

		if(empty($w)){
			$k = $h/$height;
			$w = $k*$width;
			$bestfit = true;
		}
		
		if(empty($h)){
			$k = $w/$width;
			$h = $k*$height;
			$bestfit = true;
		}
		
		$image->thumbnailImage($w, $h, true);
		
		$background = new Imagick();
		$background->newImage($w, $h, new ImagickPixel("transparent"));
		$background->setImageColorspace($image->getImageColorspace() ); 
		$background->compositeImage($image, $image->getImageCompose(), ($w-($image->getImageWidth()))/2, ($h-($image->getImageHeight()))/2);

		$background->setImageCompression(Imagick::COMPRESSION_JPEG); 		
		$background->setImageCompressionQuality(90); 
		
		$background->writeImage($filename);
	}
	
	static function cropThumbnailImage($filename, $w = null, $h = null) {
		$image = new Imagick($filename);
		$height = $image->getImageHeight();
		$width = $image->getImageWidth();

		if(empty($w)){
			$k = $h/$height;
			$w = $k*$width;
			$bestfit = true;
		}
		
		if(empty($h)){
			$k = $w/$width;
			$h = $k*$height;
			$bestfit = true;
		}
		$image->cropThumbnailImage($w, $h);
		$image->writeImage($filename);
	}
	
	static function thumbnailImage($filename, $w = null, $h = null, $bestfit = false){
		$image = new Imagick($filename);
		$height = $image->getImageHeight();
		$width = $image->getImageWidth();

		if(empty($w)){
			$k = $h/$height;
			$w = $k*$width;
			$bestfit = true;
		}
		
		if(empty($h)){
			$k = $w/$width;
			$h = $k*$height;
			$bestfit = true;
		}
		$image->thumbnailImage($w, $h, $bestfit);
		$image->writeImage($filename);
	}
	
	static function adaptiveResizeImage ($filename, $w = null, $h = null, $bestfit = false){
		$image = new Imagick($filename);
		$height = $image->getImageHeight();
		$width = $image->getImageWidth();

		if(empty($w)){
			$k = $h/$height;
			$w = $k*$width;
			$bestfit = true;
		}
		
		if(empty($h)){
			$k = $w/$width;
			$h = $k*$height;
			$bestfit = true;
		}

		$image->adaptiveResizeImage($w, $h, $bestfit);
		$image->writeImage($filename)?")":"!";
	}
	
	static function saveAsJPG($file){
		$image = new Imagick($file);
		$info = pathinfo($file);
		if($image->writeImage($info['dirname'].DIRECTORY_SEPARATOR.$info['filename'].'.jpg'))
			return $info['dirname'].DIRECTORY_SEPARATOR.$info['filename'].'.jpg';
		else
			return false;
	}
	
	static function saveAsPNG($file){
		$image = new Imagick($file);
		$info = pathinfo($file);
		
		if($image->writeImage($info['dirname'].DIRECTORY_SEPARATOR.$info['filename'].'.png'))
			return $info['dirname'].DIRECTORY_SEPARATOR.$info['filename'].'.png';
		else
			return false;
	}
	
}
?>